<script setup lang="ts">
import AccInfor from './components/acc-infor.vue';
import AccDtlItem from './components/acc-dtl-item.vue';
import type { accDtlData } from './types';
import { useScanUDI } from './composables/use-scan-udi';

const directStore = useDirectStore();
const appStore = useAppStore();

const detailObj = ref<any>({});
const manualUDI = ref('');
const manualShow = ref(false);
const options = ref([
  {
    text: '作废',
    style: {
      backgroundColor: '#EE0A24',
    },
  },
]);
const goodsList = ref<any[]>([]);
const chooseGoodsShow = ref(false);

const { list, totalNum, paginationLoading, resetAndFetchData, loadMore } = useSimplePagination(10);

const fetchOrderDocDetail = async () => {
  const response = await DirectService.queryOrderDocDetail({
    orderId: directStore.directDetailObj.orderId,
  });
  detailObj.value = response;
  directStore.setDirectDetailObj(detailObj.value);
};

/**
 * 获取细单列表数据
 */
const fetchDetail = async ({ pageNum, pageSize }: { pageNum: number; pageSize: number }) => {
  const params = {
    orderId: directStore.directDetailObj.orderId,
    pageNum,
    pageSize,
  };

  const response = await DirectService.queryOrderDtlList(params);

  return {
    list: response.list || [],
    total: response.total || 0,
  };
};

// 扫码解析 loading 状态
const scanLoading = ref(false);

// 使用扫码 composable
const { loading, errorMsg, rawCode, udiInfo, startScan, resetState } = useScanUDI({
  onSuccess: udiInfo => {
    manualUDI.value = udiInfo.di;
    // HTTP 请求会自动管理 loading，不需要手动控制
    getUDIInfo();
  },
  onError: error => {
    scanLoading.value = false;
  },
  onLoading: loading => {
    // 使用状态变量，在模板中显示自定义 loading
    scanLoading.value = loading;
  },
});

const handleDelete = async (item: any) => {
  uni.showModal({
    content: '是否确认作废该条细单',
    success: async (res: any) => {
      if (res.confirm) {
        await DirectService.deleteOrderDtl({ orderDtlId: item.orderDtlId });
        showSuccess('删除成功');
        resetAndFetchData(fetchDetail);
      }
    },
  });
};

const toAddDtl = (item: accDtlData) => {
  router.push(RouteMap.directAddDtl, { item, status: detailObj.value.userStatus });
};

const toDetailFiles = () => {
  router.push(RouteMap.directDetailFiles);
};

const handleSubmit = async () => {
  await DirectService.submitDirect({
    orderId: directStore.directDetailObj.orderId,
  });
  showSuccess('提交成功');
  appStore.setHadDoneOnDetail(true);
  router.back();
};

const handleManualClick = () => {
  manualUDI.value = '';
  manualShow.value = true;
};

const handleManualUDI = () => {
  if (!manualUDI.value) {
    showToast('请输入UDI码');
    return;
  }
  manualShow.value = false;
  getUDIInfo();
};

const getUDIInfo = async () => {
  const dtlInfor = await DirectService.queryGoodsByUdi({ udi: manualUDI.value });
  goodsList.value = dtlInfor;
  if (!dtlInfor?.length) {
    uni.showModal({
      content: '请维护货品对码关系表',
    });
    return;
  }
  if (dtlInfor?.length === 1) {
    router.push(RouteMap.directAddDtl, { item: dtlInfor[0], status: detailObj.value.userStatus });
  } else if (dtlInfor?.length > 1) {
    chooseGoodsShow.value = true;
  }
};

const handleChooseGoods = (item: any) => {
  chooseGoodsShow.value = false;
  router.push(RouteMap.directAddDtl, { item, status: detailObj.value.userStatus });
};

const handleModify = () => {
  router.push(RouteMap.directAdd);
};

onLoad(() => {
  fetchOrderDocDetail();
  resetAndFetchData(fetchDetail);
});

onShow(() => {
  console.log('detail onShow:', {
    hadDoneOnDetail: appStore.hadDoneOnDetail,
    orderDetailRefreshed: directStore.orderDetailRefreshed,
    hadDoneOnDtl: directStore.hadDoneOnDtl,
  });

  // 总单操作后刷新总单详情（只在第一次刷新）
  if (appStore.hadDoneOnDetail && !directStore.orderDetailRefreshed) {
    console.log('刷新总单详情');
    fetchOrderDocDetail();
    directStore.setOrderDetailRefreshed(true); // 标记已在detail页面刷新过
  }

  // 细单操作后刷新细单列表
  if (directStore.hadDoneOnDtl) {
    console.log('刷新细单列表');
    resetAndFetchData(fetchDetail);
    directStore.setHadDoneOnDtl(false);
  }
});

onReachBottom(() => {
  loadMore(fetchDetail);
});
</script>

<template>
  <view class="px-4 pt-10 pb-100">
    <view class="text-17 flex font-bold">
      <view>总单</view>
      <view class="color-main-3">详情</view>
    </view>
    <acc-infor :data="detailObj" class="block mt-2" @click="toDetailFiles" />
    <view class="text-17 flex font-bold mt-4">
      <view>细单</view>
      <view class="color-main-3">列表</view>
    </view>
    <up-swipe-action>
      <up-swipe-action-item
        v-for="item in list"
        :key="item.orderDtlId"
        class="block rounded-20rpx mt-4"
        :options="options"
        :disabled="detailObj.userStatus === 2"
        @click="handleDelete(item)"
      >
        <acc-dtl-item :data="item" @click="toAddDtl(item)" />
      </up-swipe-action-item>
    </up-swipe-action>
    <up-loadmore
      v-if="paginationLoading || list.length < totalNum"
      :status="paginationLoading ? 'loading' : 'loadmore'"
    />
    <view class="view-shadow mt-2">
      <app-empty
        v-show="!paginationLoading && !list.length"
        class="block py-3"
        description="暂无细单"
      />
    </view>
    <app-bottom-actions v-if="detailObj.userStatus === 1" :count="3">
      <up-select class="flex-1" iconSize="0">
        <template #text>
          <app-action-btn class="flex-1" text="操作" arrow />
        </template>
        <template #options>
          <view
            class="w-331 bg-white py-3 customer-border shadow-[0_0_12rpx_5rpx_rgba(210,210,210,.1)]"
          >
            <view
              class="py-3 flex items-center justify-center border-2 border-solid border-gray-100 border-l-0 border-r-0 border-t-0"
              @click="handleManualClick"
            >
              <app-icon class="block h-32" name="jianpan_keyboard" size="32rpx" multi />
              <view class="ml-2 text-14">手动输入UDI码</view>
            </view>
            <view class="py-3 flex items-center justify-center" @click="handleModify">
              <app-icon class="block h-32" name="xingzhuangjiehe1" size="32rpx" multi />
              <view class="ml-2 text-14">修改总单信息</view>
            </view>
          </view>
        </template>
      </up-select>
      <app-action-btn
        class="flex-1"
        text="扫描UDI码"
        icon="weixinsaoyisao_weixin-scan"
        type="primary"
        @click="startScan"
      />
      <app-action-btn
        class="flex-1"
        text="提交总单"
        icon="xingzhuangjiehe"
        type="main"
        @click="handleSubmit"
      />
    </app-bottom-actions>
    <up-modal
      :show="manualShow"
      title="手动输入UDI码"
      showCancelButton
      @confirm="handleManualUDI"
      @cancel="manualShow = false"
    >
      <up-input v-model="manualUDI" border="bottom" placeholder="输入UDI码" class="mt-4" />
    </up-modal>
    <!-- 扫码解析 Loading，独立于 HTTP 请求的 loading -->
    <up-loading-page
      :loading="scanLoading"
      loadingText="解析UDI码中..."
      :bgColor="'rgba(0, 0, 0, 0.5)'"
    />
    <up-modal
      :show="chooseGoodsShow"
      title="选择品种"
      showCancelButton
      :showConfirmButton="false"
      @cancel="chooseGoodsShow = false"
    >
      <view class="mt-3">
        <view
          v-for="(item, index) in goodsList"
          :key="item.goodsId || index"
          class="border-solid border-2 border-gray-200 rounded-3 py-3 px-4 mb-3 flex items-center justify-between"
          @click="handleChooseGoods(item)"
        >
          <view class="flex-1">
            <view class="text-14 font-bold"> {{ item.goodsId }}/{{ item.goodsName }} </view>
            <view class="color-gray-5 mt-2">规格: {{ item.goodsType }}</view>
            <view class="color-gray-5 mt-1">生产厂家: {{ item.factoryName }}</view>
          </view>
          <up-icon class="ml-3" name="arrow-right" size="14" color="#c8c9cc"></up-icon>
        </view>
      </view>
    </up-modal>
  </view>
</template>

<style scoped>
/* stylelint-disable-next-line selector-class-pattern */
:deep(.u-select__options__wrap) {
  top: -244rpx !important;
}

:deep(.u-select__options) {
  background: transparent !important;
  border: none !important;
}
</style>
